﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Security.Claims;
using System.Security.Cryptography;
using System.Threading.Tasks;
using System.Web;
using System.Linq;
using System.Web.Http;
using System.Web.Http.ModelBinding;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.OAuth;
using ezCloud.Api.Models;
using ezCloud.Api.Providers;
using ezCloud.Api.Results;
using ezCloud.Data;

namespace ezCloud.Api.Controllers
{
    [RoutePrefix("api/Staff")]
    public class StaffController : ApiController
    {
        private ApplicationUserManager _userManager;

        public ApplicationUserManager UserManager
        {
            get
            {
                return _userManager ?? Request.GetOwinContext().GetUserManager<ApplicationUserManager>();
            }
            private set
            {
                _userManager = value;
            }
        }

        [HostAuthentication(DefaultAuthenticationTypes.ExternalBearer)]
        [Route("GetAllStaff")]
        public List<Staffs> GetAllStaffs()
        {
            var user = Common.UserUtitily.getUserProfile();
            var context = new ezCloudDataContext();
            return context.Staffs.Where(staff => staff.HotelId == user.HotelId).ToList();
        }



        [HostAuthentication(DefaultAuthenticationTypes.ExternalBearer)]
        [Route("CreateStaff")]
        public async Task<IHttpActionResult> CreateStaff(StaffViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            var context = new ezCloudDataContext();
            
            var currentClientUser = Common.UserUtitily.getUserProfile();
           /* string currentHotelName = (from hotel in context.Hotels
                                       where hotel.HotelId == currentClientUser.HotelId
                                       select hotel).FirstOrDefault().HotelName;*/
            var email = context.Staffs.Where(s => s.HotelId == currentClientUser.HotelId && s.Email == model.Email).FirstOrDefault();
            if (email != null)
            {
                ModelState.AddModelError("Email", "EMAIL_CONFLICT");
                return BadRequest(ModelState);
            }
            string EmailNoConflict = model.UserName + "@ezCloud_" + currentClientUser.HotelId + ".vn";
            string StaffUserNameBaseOnHotelID = model.UserName + "@" + currentClientUser.HotelId;

            var user = new ApplicationUser()
            {
                UserName = StaffUserNameBaseOnHotelID,
                Email = EmailNoConflict
            };

            user.PhoneNumber = null;
            user.EmailConfirmed = true;
            user.EmailConfirmToken = null;
            user.DefaultHotelId = 0;

            IdentityResult result = await UserManager.CreateAsync(user, model.Password);

            if (!result.Succeeded)
            {
                return GetErrorResult(result);
            }
            Staffs staffs = new Data.Staffs();
            staffs.UserId = user.Id;
            staffs.HotelId = currentClientUser.HotelId;
            staffs.Email = model.Email;
            staffs.Description = model.Description;
            context.Staffs.InsertOnSubmit(staffs);
            context.SubmitChanges();
            var roleresult = UserManager.AddToRole(user.Id, model.StaffRole);
            await UserManager.UpdateAsync(user);

            

            return Ok();
        }


        [Route("UserInfoByStaff")]
        public AspNetUsers UserInfoByStaff(Staffs staff)
        {
            var context = new ezCloudDataContext();
            return context.AspNetUsers.Where(user => user.Id == staff.UserId).FirstOrDefault();
        }

        private IHttpActionResult GetErrorResult(IdentityResult result)
        {
            if (result == null)
            {
                return InternalServerError();
            }

            if (!result.Succeeded)
            {
                if (result.Errors != null)
                {
                    foreach (string error in result.Errors)
                    {
                        ModelState.AddModelError("", error);
                    }


                    if (ModelState.IsValid)
                    {
                        // No ModelState errors are available to send, so just return an empty BadRequest.
                        return BadRequest();
                    }

                    return BadRequest(ModelState);
                }
            }
            return null;
        }

    }
}